import axios from 'axios';
import { Message, MessageBox, Loading } from 'element-ui';
import { getToken } from '@/common/token'
import {_baseUrl} from '@/common/config'

const $baseUrl = _baseUrl;
const $axios = axios.create({
    baseURL: $baseUrl,
    //baseURL: '',
    headers: { 'X-Requested-With': 'XMLHttpRequest' },
    // `withCredentials` 表示跨域请求时是否需要使用凭证(即是否支持session)
    //withCredentials: true
});


$axios.interceptors.request.use((config) => {
    const token = getToken();
    if (token) {
        config.headers['Authorization'] = getToken();
    }
    return config;
}, error => {
    return Promise.reject(error);
});

export const $ajax = function (getAxiosPromise, options) {

    let promise = new Promise((resolve) => {

        try {
            let loading;
            //显示加载提示代码
            if (options && options.hasLoading) {
                loading = Loading.service({
                    fullscreen: options.fullscreen === true ? true : false,
                    target: options.target || document.body,
                    lock: true,
                    background: 'rgba(150, 150, 150, 0.3)'
                });
            }

            getAxiosPromise()
                .then(res => {//处理成功响应

                    //关闭加载提示
                    if (options && options.hasLoading) {
                        loading.close();
                    }

                    let result = res.data;//获取服务器的响应结果


                    if (!result.logined && result.logined === undefined) {
                        //服务器响应数据无已登录标志属性logined
                        resolve(result);//由then方法的参数（一个函数）继续处理响应结果
                        return result;
                    }

                    if (!result.logined) {
                        //服务器响应结果的已登录标志属性logined的值为false

                        Message({
                            message: '您已下线，请登录！',
                            type: 'warning',
                            duration: 1500,
                            onClose() {
                                window.top.location.href = 'index.html';
                            }
                        });

                        return result;
                    }

                    if (result.authorized === undefined) {
                        resolve(result);//由then方法的参数（一个函数）继续处理响应结果

                    }

                    if (!result.authorized) {
                        Message({
                            message: '权限不足！',
                            type: 'error'
                        });
                        return result;
                    }

                    //由then方法的参数（一个函数）继续处理响应结果
                    resolve(result);

                    return result;

                })
                .catch(err => {//处理错误响应

                    //关闭加载提示
                    if (options && options.hasLoading) {
                        loading.close();
                    }

                    console.log(err);//控制台打印错误信息



                    //若错误对象不存在response属性或者该属性值可转换为false
                    if (!err.response) {

                        Message({
                            message: '错误: ' + err.message,
                            type: 'error'
                        });

                        return;
                    }

                    //若服务器没有响应
                    if (err.response.status == 0) {
                        Message({
                            message: `地址 ${err.config.url} 没有响应，可能服务器不可用或者地址不正确。`,
                            type: 'error'
                        });
                        return;
                    }

                    Message({
                        message: `响应错误：${err.response.status}`,
                        type: 'error'
                    });

                });

        } catch (error) {//发生异常

            console.log(error);

            Message({
                message: '错误:' + error.message,
                type: 'error'
            });

            throw error;

        }

    });

    return promise;

};


export const $myoprate = function (getAxiosPromise, confirmInfo) {

    let promise = new Promise((resolve) => {

        if (confirmInfo && confirmInfo.message && confirmInfo.title) {

            MessageBox.confirm(confirmInfo.message, confirmInfo.title, {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                confirmInfo.hasLoading = true;//默认带有加载提示
                $ajax(getAxiosPromise, confirmInfo)
                    .then((result) => {

                        if (result.success) {


                            if (confirmInfo && confirmInfo.postMsg) {//是否提示后执行函数

                                Message({
                                    message: result.message,
                                    type: 'success',
                                    duration: (confirmInfo && confirmInfo.duration && !isNaN(confirmInfo.duration)) ? parseInt(confirmInfo.duration) : 1500,
                                    onClose: function () {
                                        resolve(result);

                                    }
                                });

                            } else {

                                Message({
                                    message: result.message,
                                    type: 'success',
                                    duration: (confirmInfo && confirmInfo.duration && !isNaN(confirmInfo.duration)) ? parseInt(confirmInfo.duration) : 1500
                                });
                                resolve(result);


                            }

                        } else {

                            MessageBox.alert(result.message, '错误', {
                                confirmButtonText: '确定',
                                type: 'error'
                            });

                        }

                        return result;

                    });

            }).catch(() => {
                Message({
                    message: '您已取消操作！',
                    type: 'info'
                });
            });

        } else {

            if (!confirmInfo) confirmInfo = {};

            confirmInfo.hasLoading = true;//默认具有加载提示
            $ajax(getAxiosPromise, confirmInfo)
                .then((result) => {

                    if (result.success) {

                        if (confirmInfo && confirmInfo.postMsg) {//是否提示后执行函数

                            Message({
                                message: result.message,
                                type: 'success',
                                duration: (confirmInfo && confirmInfo.duration && !isNaN(confirmInfo.duration)) ? parseInt(confirmInfo.duration) : 1500,
                                onClose: function () {
                                    resolve(result);
                                }
                            });


                        } else {
                            Message({
                                message: result.message,
                                type: 'success',
                                duration: (confirmInfo && confirmInfo.duration && !isNaN(confirmInfo.duration)) ? parseInt(confirmInfo.duration) : 1500
                            });
                            resolve(result);
                        }



                    } else {

                        MessageBox.alert(result.message, '错误', {
                            confirmButtonText: '确定',
                            type: 'error'
                        });

                    }

                    return result;

                });


        }

    });

    return promise;

};

export const $myGet = function (url, config) {

    let promise = new Promise((resolve) => {

        $ajax(() => $axios.get(url, config), config)
            .then((result) => {
                resolve(result);
                return result;
            });

    });

    return promise;
};

export const $myPost = function (url, data, config) {

    return $myoprate(() => $axios.post(url, data, config), config);

};

export const $myPut = function (url, data, config) {

    return $myoprate(() => $axios.put(url, data, config), config);

};

export const $myDelete = function (url, config) {

    return $myoprate(() => $axios.delete(url, config), config);

};


export const $myLogined = function () {

    return $myGet('/pub/currUser');

};

/*
以application/x-www-form-urlencoded编码格式，向服务器发出post请求，返回promise，
then方法的参数是一个函数，该函数的参数为服务器发送的未经包装响应数据
*/
export const $post = function (url, data, config) {
    if (!config) {
        config = {};
    }

    if (!config.headers) {
        config.headers = { "Content-Type": 'application/x-www-form-urlencoded' };
    } else {
        config.headers['Content-Type'] = 'application/x-www-form-urlencoded';
    }

    config.transformRequest = [function (data) {

        if (!data || typeof (data) === 'string') {
            return data;
        }

        if (!(typeof (data) === 'object')) {
            return data;
        }


        let params = [];
        for (let prop in data) {
            if (data[prop] instanceof Array) {
                let arr = data[prop];
                for (let i = 0; i < arr.length; i++) {
                    params.push(prop + "=" + arr[i]);
                }
            } else {
                params.push(prop + "=" + data[prop]);
            }

        }
        return params.join("&");

    }];

    return $myoprate(() => $axios.post(url, data, config), config);

};

/*
给Vue添加原型方法 向服务器发出get请求，返回promise，
then方法的参数是一个函数，该函数的参数为服务器发送的未经包装响应数据
*/
export const $get = function (url, data, config) {

    if (!config) {
        config = {};
    }

    config.params = data;

    return $myGet(url, config);

}




